import logging

from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer

from app.models.user import User
from app.schemas.token import APIResponse
from app.security.auth_service import auth_service

# 配置日志
logger = logging.getLogger(__name__)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")


async def get_current_user(
        token: str = Depends(oauth2_scheme),
        request: Request = None
) -> User:
    """
    获取当前用户
    """
    # 输出请求信息用于调试
    if request:
        logger.debug(f"请求路径: {request.url.path}")
        logger.debug(f"请求方法: {request.method}")
        logger.debug(f"请求头: {request.headers}")
        logger.debug(f"请求参数: {request.query_params}")
    
    logger.debug(f"开始解析认证令牌: {token[:10]}...")
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="不能验证用户登录凭证。",
        headers={"WWW-Authenticate": "Bearer"},
    )

    user = await auth_service.get_current_user_from_token(token)
    if user is None:
        logger.error("令牌验证失败，用户为空")
        raise credentials_exception
    logger.debug(f"当前登录用户：{user}")
    return user


async def get_current_active_user(
        current_user: User = Depends(get_current_user),
) -> User:
    """
    获取当前活跃用户
    """
    logger.debug(f"current_user@get_current_active_user:{current_user}")
    if not current_user.is_active:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"用户 [{current_user.login_name}] 未激活。", data=None)
        )
    return current_user


async def get_current_active_superuser(
        current_user: User = Depends(get_current_active_user),
) -> User:
    """
    获取当前超级用户
    """
    if not current_user.is_superuser:
        logger.error(f"权限不足: 用户 {current_user.login_name} 不是超级用户")
        raise HTTPException(
            status_code=401,
            detail=APIResponse(code=401, msg=f"当前用户 [{current_user.login_name}] 权限不足。", data=None)
        )
    return current_user


async def get_current_user_tenant_id(
        current_user: User = Depends(get_current_active_user),
) -> str:
    """
    获取当前用户的租户 ID
    """
    if not current_user.tenant_id:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"当前用户{current_user.login_name},没有租户信息。", data=None)
        )
    return current_user.tenant_id


class PermissionRequired:
    """
    权限依赖类，用于检查用户是否具有访问特定资源的权限
    """

    def __init__(self, resource_code: str):
        """
        初始化权限检查依赖
        :param resource_code: 资源代码
        """
        self.resource_code = resource_code

    async def __call__(
            self,
            # db: AsyncSession = Depends(get_db),
            current_user: User = Depends(get_current_active_user)
    ) -> User:
        """
        检查用户是否有权限访问资源
        """
        logger.debug(f"检查权限,current_user:{current_user}")
        # # 超级用户拥有所有权限
        # if current_user.is_superuser:
        #     return current_user
        #
        # # 获取用户的角色
        # # 直接使用用户对象的角色关系，避免额外查询
        # user_roles = current_user.roles
        #
        # # 检查用户角色是否关联该资源
        # resource_stmt = select(Resource).where(Resource.code == self.resource_code)
        # resource_result = await db.execute(resource_stmt)
        # resource = resource_result.scalar_one_or_none()
        #
        # if not resource:
        #     raise HTTPException(
        #         status_code=status.HTTP_403_FORBIDDEN,
        #         detail="请求的资源不存在"
        #     )
        #
        # # 检查用户的角色是否关联到该资源
        # # 通过检查角色列表中的每个角色是否关联到资源
        # resource_role_ids = [role.id for role in resource.roles]
        # user_role_ids = [role.id for role in user_roles]
        #
        # # 检查是否有交集
        # if not set(resource_role_ids) & set(user_role_ids):
        #     raise HTTPException(
        #         status_code=status.HTTP_403_FORBIDDEN,
        #         detail="用户没有权限访问此资源"
        #     )

        return current_user
